//
//  QWHomeController.m
//  qwm
//
//  Created by kevin on 2023/3/23.
//

#import "QWHomeController.h"
#import "QABannerView.h"
#import "QWHomeModel.h"
#import "QWWebviewController.h"
#import "QADoctorItemCell.h"
#import "QAMenusCell.h"
#import "QADocHeaderView.h"
#import "QADoctorListController.h"
#import "QWDoctorDetailController.h"

@interface QWHomeController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *bannerDataArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *doctorDataArr;
@end

@implementation QWHomeController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
//    [self hiddenLeftBarButtonItem];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    // 监测网络情况
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name: kReachabilityChangedNotification
                                               object: nil];
    
    [self tableView];
    [self loadAllData];
}

#pragma mark - tabbleView
- (UITableView *)tableView{
    if(!_tableView){
        _tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionFooterHeight=0;
        _tableView.estimatedSectionHeaderHeight=0;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.showsHorizontalScrollIndicator=NO;
        
        _tableView.delegate =self;
        _tableView.dataSource =self;
        
        [_tableView registerClass:[QADocHeaderView class] forHeaderFooterViewReuseIdentifier:@"QADocHeaderView"];
        [_tableView registerClass:[QADoctorItemCell class] forCellReuseIdentifier:@"QADoctorItemCell"];
        [_tableView registerClass:[QAMenusCell class] forCellReuseIdentifier:@"QAMenusCell"];

        _tableView.backgroundColor=Color_TableView_Gray;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//铺满全屏

//        [_tableView addRefreshHeaderWithTarget:self action:@selector(loadPullDownRefreshDataInfo)];//下拉刷新
//        [_tableView addLoadMoreFooterWithTarget:self action:@selector(loadPullUpRefreshDataInfo)];//上拉加载
        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _tableView;
}
#pragma mark- UITableViewDelegate,UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0? kScreenWidth/2.0 : 60.0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0? 1 :_doctorDataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        QAMenusCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QAMenusCell"];
        cell.menuItemClickBlock = ^(NSDictionary * _Nonnull data) {
            [self menuButtonClick:data];
        };
        return cell;
    }else{
        QADoctorItemCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QADoctorItemCell"];
        QADoctorModel*model = _doctorDataArr[indexPath.row];
        cell.model = model;
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section != 0){
//        QADoctorModel*model = _doctorDataArr[indexPath.row];
//        NSString *url = [URL_DOCTOR_INFO stringByAppendingFormat:@"?id=%@&from=app",model.id];
//        [self jumToWebView:url];
        
        QADoctorModel*model = _doctorDataArr[indexPath.row];
        QWDoctorDetailController *detailVC = [[QWDoctorDetailController alloc]init];
        detailVC.doctorModel = model;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
  
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        QABannerView *bannerView =[[QABannerView alloc]init];
        bannerView.showArr = self.bannerDataArr;
        __weak __typeof(self) weakSelf = self;
        bannerView.bannerClickBlock = ^(QABannerModel * _Nonnull bannerModel) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf jumToWebView:bannerModel.imgTarget];
        };
        [self.view addSubview:bannerView];
        return bannerView;
    }else {
        QADocHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"QADocHeaderView"];
        headerView.moreClickBlock = ^{
            QADoctorListController *docListVC =[[QADoctorListController alloc]init];
            docListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:docListVC animated:YES];
        };
        return headerView;
    }
    return [UIView new];
}

#pragma mark - 菜单按钮-跳转
- (void)menuButtonClick:(NSDictionary *)data{
    NSString *url = data[@"url"];
    if(!IsStringEmpty(url)){
        [self jumToWebView:url];
    }
}

#pragma mark - 所有数据-请求
- (void) loadAllData{
    [self loadBannerData]; //banner数据
    [self loadDoctorListData];//医生列表数据
}
#pragma mark - banner-请求
- (void)loadBannerData{
    HXGetRequest * request = [[HXGetRequest alloc] initWithRequestUrl:URL_BANNER argument:[NSDictionary dictionary]];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest *request, NSDictionary *result, BOOL success) {
        NSArray *resArr =(NSArray *)result;
        NSMutableArray *arr =[QABannerModel mj_objectArrayWithKeyValuesArray:resArr];
        [self.bannerDataArr removeAllObjects];
        self.bannerDataArr = arr;
        [self.tableView reloadData];
        NSLog(@"");
    } failure:^(__kindof HXRequest *request, NSString *errorInfo) {
        //错误
        NSLog(@"%@",errorInfo);
    }];
}

#pragma mark - 医生列表-请求
- (void)loadDoctorListData{
    HXGetRequest * request = [[HXGetRequest alloc] initWithRequestUrl:URL_DOCTOR_LIST argument:[NSDictionary dictionary]];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest *request, NSDictionary *result, BOOL success) {
        NSArray *resArr =(NSArray *)result;
        NSMutableArray *arr =[QADoctorModel mj_objectArrayWithKeyValuesArray:resArr];
        [self.doctorDataArr removeAllObjects];
        self.doctorDataArr = arr;
        [self.tableView reloadData];
        NSLog(@"");
    } failure:^(__kindof HXRequest *request, NSString *errorInfo) {
        //错误
        NSLog(@"%@",errorInfo);
    }];
}

#pragma mark - webview - 跳转
- (void)jumToWebView:(NSString *)url{
    QWWebviewController *webviewVC =[[QWWebviewController alloc]init];
    webviewVC.url = url;
    webviewVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webviewVC animated:YES];
}

#pragma mark -网络监听
- (void)reachabilityChanged:(NSNotification *)note {
    // 连接改变
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    //处理连接改变后的情况
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (status != NotReachable) {
       if(self.bannerDataArr == nil || self.doctorDataArr == nil) [self loadAllData];
    }
}

@end
